package com.tianci.appstore.ui.list.clearcache;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tianci.appstore.R;
import com.tianci.appstore.controller.manager.ClearCacheManagerController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.dialog.ConfirmProcessDialog;
import com.tianci.appstore.ui.list.ListBlock;
import com.tianci.appstore.ui.list.manage.ManageBaseListView;
import com.tianci.appstore.ui.list.manage.MultiSelectUIListener;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.OnButtonClickListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

import java.util.List;

public class ClearCacheListView extends ManageBaseListView implements
        MultiSelectUIListener, OnClickListener, OnButtonClickListener, OnClearCacheStateListener {
    private LinearLayout btnLayout;
    //private Button selectButton;
    //private Button cancelButton;
    private Button clearallButton;
    private boolean inSelectMode = false;
    private TextView countSizeText;

    private static final int UPDATE_COUNT = 10;
    private static final int SELECT_BTN_ID = 201;
    private static final int CANCEL_BTN_ID = 202;
    private static final int CLEAR_ALL_BTN_ID = 203;
    private float mCacheSize = 0.0f;

    private LinearLayout.LayoutParams btnParams;
    private boolean mClearAll = true;

    private boolean firstDataLoaded = false;

    public ClearCacheListView(Context context) {
        super(context, ListType.CLEAR_CACHE_LIST);
        // TODO Auto-generated constructor stub
        mController.setMultiSelectUIListener(this);
        initTopRightLayout();
        ClearCacheManagerController.getInstance().registExternalStorageChangedListener();
        ClearCacheManagerController.getInstance().setClearCacheStateListener(this);
        ClearCacheManagerController.getInstance().getLocalApps();
        setLoadingVisible(true);
    }

    private void initTopRightLayout() {
        LinearLayout rightTopLayout = new LinearLayout(mContext);
        rightTopLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);

        countSizeText = UICommon.newTextView(mContext, rightTopTextSize, R.color.btnColor);
        countSizeText.setPadding(SkyConstants.Div(20), 0, SkyConstants.Div(20), 0);
        rightTopLayout.addView(countSizeText);

        FrameLayout layout = new FrameLayout(mContext);
//        ImageView btnTopImage = new ImageView(mContext);
//        SkinManager.setBackground(btnTopImage, R.drawable.pic_line);
//        LayoutParams dividerParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP);
//        layout.addView(btnTopImage, dividerParams);
        rightTopLayout.addView(layout);
        btnLayout = new LinearLayout(mContext);
        btnLayout.setPadding(SkyConstants.Div(22), 0, SkyConstants.Div(22), 0);
        layout.addView(btnLayout, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        btnParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        btnParams.setMargins(SkyConstants.Div(10), 0, SkyConstants.Div(10), 0);
        //selectButton = newButton(SELECT_BTN_ID, R.string.select);
        //btnLayout.addView(selectButton, btnParams);
        //cancelButton = newButton(CANCEL_BTN_ID, R.string.cancel);
        clearallButton = newButton(CLEAR_ALL_BTN_ID, R.string.clear);
        btnLayout.addView(clearallButton, btnParams);
        LayoutParams topRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
        topRightParams.setMargins(0, SkyConstants.Div(85), SkyConstants.Div(75), 0);
        this.addView(rightTopLayout, topRightParams);
    }

    private Button newButton(int btnId, int strId) {
        Button btn = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        SkinManager.setBackground(btn, R.drawable.search_selector);
        //btn.setPadding(SkyConstants.Div(27), 0, SkyConstants.Div(27), SkyConstants.Div(6));
        btn.setText(strId);
        btn.setId(btnId);
        btn.setOnClickListener(this);
        return btn;
    }

    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_LIST:
                    refreshListData((List<SkyListAppData>) msg.obj);
                    break;
                case UPDATE_COUNT:
                    refreshCountAndSize(msg.arg1, msg.getData().getFloat("cache"));
                    break;
                case DELAY_DISSMISS_DIALOG:
                    dialog.dismiss();
                    break;
                case UPDATE_SUCCESS_STATE:
                    dialog.enterResultState(String.format(getResources().getString(R.string.clear_complete), getCacheStringBySize(mCacheSize)));
                    break;
                case UPDATE_FAILED_STATE:
                    dialog.enterFailedState((List<SkyListAppData>) msg.obj, getResources().getString(R.string.clear_cache_failed));
                    break;
            }
            super.handleMessage(msg);
        }
    };


    private void refreshCountAndSize(int appCount, float cache) {
        if (appCount == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_app_cache));
            setBtnEnabled(clearallButton, false);
        } else {
            setEmptyTipVisible(false, null);
            setBtnEnabled(clearallButton, true);
            clearallButton.requestFocus();
        }
        String str = mContext.getResources().getString(R.string.app_count_str);
        countSizeText.setText(String.format("%d%s", appCount, str));
        clearallButton.setText(getResources().getString(R.string.clear_all_cache) + addBrackets(getCacheStringBySize(cache)));
    }

    public String addBrackets(String content) {
        return "(" + content + ")";
    }

    public String getCacheStringBySize(float cache) {
        String temp = "";
        if (cache >= 1024) {
            temp = String.format("%.1fMB", cache / SkyConstants.BTOK);
        } else {
            temp = cache + "KB";
        }
        return temp;
    }

    private void refreshListData(List<SkyListAppData> dataList) {
        if (dataList == null || dataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_app_cache));
            return;
        }
        setLoadingVisible(false);
        setEmptyTipVisible(false, null);
        mController.setDataList(dataList);
        setSelectMode(true);
        if (!firstDataLoaded) {
            TipToast.getInstance(mContext).showToast(
                    SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                    mContext.getResources().getString(R.string.clear_select_tip),
                    3500, Gravity.CENTER);
            firstDataLoaded = true;
        }
        resetFocus();
    }

    private void setSelectMode(boolean selMode) {
        if (this.inSelectMode == selMode)
            return;
        this.inSelectMode = selMode;
        if (selMode) {
            //btnLayout.removeAllViews();
            //btnLayout.addView(cancelButton, btnParams);
            //btnLayout.addView(clearallButton, btnParams);
            //clearallButton.setText(getResources().getString(R.string.clear));
            //setBtnEnabled(clearallButton, true);

//            ListBlock.setSelectMode(inSelectMode);
            setInSelectMode(inSelectMode);
            for (int i = 0; i < listFlipper.getChildCount(); i++) {
                SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    ListBlock block = (ListBlock) child.getChildAt(j);
                    block.refreshSelectState();
                }
            }
            mController.clearSelectedDataList();
            resetFocus();
        } else {
            //btnLayout.removeAllViews();
            //btnLayout.addView(selectButton, btnParams);
            //btnLayout.addView(clearallButton,btnParams);
            //clearallButton.setText(getResources().getString(R.string.clear_all_cache) 
            //        + addBrackets(getCacheStringBySize(ClearCacheManagerController.getInstance(mContext).getTotalCacheSize())));
            //setBtnEnabled(clearallButton, true);
            mController.clearSelectedDataList();
//            ListBlock.setSelectMode(false);
            setInSelectMode(false);
            for (int i = 0; i < listFlipper.getChildCount(); i++) {
                SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    ListBlock block = (ListBlock) child.getChildAt(j);
                    block.refreshSelectState();
                }
            }
            resetFocus();
        }
    }

    @Override
    public void OnSelectCountChanged(int count) {
        // TODO Auto-generated method stub
        if (inSelectMode) {
            //setBtnEnabled(clearallButton, count != 0);
            if (count != 0) {
                clearallButton.setText(getResources().getString(R.string.clear));
                clearallButton.invalidate();
            } else {
                clearallButton.setText(getResources().getString(R.string.clear_all_cache)
                        + addBrackets(getCacheStringBySize(ClearCacheManagerController.getInstance().getTotalCacheSize())));
                clearallButton.invalidate();
            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case SELECT_BTN_ID:
                if (!inSelectMode)
                    setSelectMode(!inSelectMode);
                break;
            case CANCEL_BTN_ID:
                if (inSelectMode) {
                    setSelectMode(!inSelectMode);
                    resetFocus();
                }
                break;
            case CLEAR_ALL_BTN_ID:
                if (mController.getSelectedDataList().size() == 0) {
                    mCacheSize = ClearCacheManagerController.getInstance().getTotalCacheSize();
                    mClearAll = true;
                } else {
                    mClearAll = false;
                    mCacheSize = 0;
                    for (SkyListAppData data : mController.getSelectedDataList()) {
                        mCacheSize += data.getSize();
                    }
                }
                if (dialog == null) {
                    dialog = new ConfirmProcessDialog(mContext);
//                    ColorButton btn = new ColorButton(mContext, R.string.cancel, R.drawable.btn_gray, R.drawable.btn_gray_focus);
//                    dialog.addButton(btn, 0, false);
//                    ColorButton btn2 = new ColorButton(mContext, R.string.clear, R.drawable.btn_green, R.drawable.btn_green_focus);
//                    dialog.addButton(btn2, 1, true);
//                    dialog.setButtonClickListener(this);
                } else {
                    dialog.initStatus();
                }
//                String contentStr = "";
                if (mController.getSelectedDataList().size() == 1) {
                    dialog.setIconTitle(mController.getSelectedDataList().get(0), mController.getSelectedDataList().get(0).getTitle());
//                    contentStr = String.format(getResources().getString(R.string.confirm_clear_cache),
//                            mController.getSelectedDataList().get(0).getTitle());
                } else {
                    dialog.setIconTitle(SkinManager.getResDrawable(R.drawable.icon_qingchu), getResources().getString(R.string.clear_cache));
//                    contentStr = getResources().getString(R.string.select_clear_cache_size) + 
//                            addBrackets(getCacheStringBySize(ClearCacheManagerController.getInstance(mContext).getTotalCacheSize()));
                }
//                dialog.setContent(contentStr);
                if (mClearAll) {
                    ClearCacheManagerController.getInstance().clearAllCache();
                } else {
                    ClearCacheManagerController.getInstance().clearCacheAppList(mController.getSelectedDataList());
                }
                mController.clearSelectedDataList();
                dialog.enterWaitState(String.format(getResources().getString(R.string.clearing_cache), mCacheSize));
                dialog.show();
                //setSelectMode(false);
                break;
        }
    }

    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        ClearCacheManagerController.getInstance().destroy();
        if (dialog != null) {
            dialog.onDestory();
        }
        super.destroyController();
    }

    @Override
    public boolean processKeyDown(int keyCode) {
        // TODO Auto-generated method stub
//        if(keyCode == KeyEvent.KEYCODE_BACK)
//        {
//            if(inSelectMode)
//            {
//                //setSelectMode(!inSelectMode);
//                return true;
//            }
//        }
        return false;
    }

    private ConfirmProcessDialog dialog;
    private String dlgPkgName;
    private boolean silent = false;

    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
        dlgPkgName = data.getPkgName();
//        if (dialog == null)
//            dialog = new CommonAppOpDialog(mContext);
//        String contentStr = getResources().getString(R.string.select_clear_cache_size)
//                + getCacheStringBySize(data.getSize());
//        dialog.setData(data.getId(), data.getTitle(), contentStr, data.getIconUrl());
//        ColorButton btn = new ColorButton(mContext, R.string.cancel, R.drawable.btn_gray,
//                R.drawable.btn_gray_focus);
//        dialog.addButton(btn, 0, false);
//        ColorButton btn2 = new ColorButton(mContext, R.string.clear, R.drawable.btn_green,
//                R.drawable.btn_green_focus);
//        dialog.addButton(btn2, 1, true);
//        dialog.show();
    }

    @Override
    public void onClick(int index) {
        // TODO Auto-generated method stub
        if (index == 0) {
            dialog.hide();
        } else if (index == 1) {
            if (mClearAll) {
                ClearCacheManagerController.getInstance().clearAllCache();
            } else {
                ClearCacheManagerController.getInstance().clearCacheAppList(mController.getSelectedDataList());
            }
            mController.clearSelectedDataList();
            dialog.enterWaitState(getResources().getString(R.string.clearing_cache));
        }
    }

    @Override
    public void appSizeChange(List<SkyListAppData> appDatas) {
        Message msg = mainHandler.obtainMessage(UPDATE_LIST);
        msg.obj = appDatas;
        mainHandler.sendMessage(msg);
    }

    @Override
    public void clearCache(List<SkyListAppData> appDatas, float releaseSpace) {
        if (appDatas.size() > 0) {
            Message msg = mainHandler.obtainMessage(UPDATE_FAILED_STATE);
            msg.obj = appDatas;
            mainHandler.sendMessage(msg);
            mController.clearSelectedDataList();
        } else {
            mainHandler.sendEmptyMessage(UPDATE_SUCCESS_STATE);
            mainHandler.sendEmptyMessageDelayed(DELAY_DISSMISS_DIALOG, 2000);
        }
    }

    @Override
    public void refreshCacheData(int appCount, float cache) {
        Message msg = mainHandler.obtainMessage(UPDATE_COUNT);
        msg.arg1 = appCount;
        Bundle bundle = new Bundle();
        bundle.putFloat("cache", cache);
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
    }
}
